package cn.com.yx.ms.service.impl;

import cn.com.yx.ms.application.web.ApiQueryBase;
import cn.com.yx.ms.domain.dbmodel.DevEquStore;
import cn.com.yx.ms.domain.dbmodel.LiveConfigMain;
import cn.com.yx.ms.domain.dbmodel.LiveConfigMedia;
import cn.com.yx.ms.domain.live.*;
import cn.com.yx.ms.domain.mq.MqSelectedDevModel;
import cn.com.yx.ms.domain.mq.upstream.MqPushLiveConfigModel;
import cn.com.yx.ms.persistence.DevEquStoreMapper;
import cn.com.yx.ms.persistence.LiveConfigMainMapper;
import cn.com.yx.ms.persistence.LiveConfigMediaMapper;
import cn.com.yx.ms.service.ILiveService;
import cn.com.yx.ms.service.IMqService;
import cn.yx.framework.configuration.ApiCode;
import com.github.pagehelper.util.StringUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.text.Collator;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * ApphubServiceImpl
 */
@Service
@Transactional
public class LiveServiceImpl implements ILiveService {

    @Resource
    private IMqService iMqService;
    @Resource
    private LiveConfigMainMapper liveConfigMainMapper;
    @Resource
    private LiveConfigMediaMapper liveConfigMediaMapper;
    @Resource
    private DevEquStoreMapper equStoreMapper;

    // region << 直播设备列表 >>
    @Override
    public List<LiveDevModel> findLiveDevs(ApiQueryBase apiQueryBase) {
        return equStoreMapper.findLiveDevs(apiQueryBase);
    }

    @Override
    public LiveDevModel findLive(String equipmentguid) {
        return equStoreMapper.findLiveDev(equipmentguid);
    }

    @Override
    public ApiCode saveLiveDev(DevEquStore devEquStore) {
        ApiCode apiCode = ApiCode.APP_100200;

        // todo 校验

        boolean isnew = false;
        DevEquStore des = equStoreMapper.selectByPrimaryKey(devEquStore.getEquipmentguid());
        if (des == null) {
            isnew = true;
            des = new DevEquStore();
            des.setEquipmentguid(UUID.randomUUID().toString());
        }
        des.setEquipmentno(devEquStore.getEquipmentno());
        des.setSname(devEquStore.getSname());
        des.setDevSn(devEquStore.getEquipmentno());
        if (!isnew) {
            equStoreMapper.updateByPrimaryKey(des);
        } else {
            des.setCreatetime(new Date());
            des.setCatalogid("root");
            equStoreMapper.insert(des);
        }

        return apiCode;
    }

    @Override
    public ApiCode deleteLiveDev(String equipmentguid) {
        ApiCode apiCode = ApiCode.APP_100200;
        int result = equStoreMapper.deleteByPrimaryKey(equipmentguid);
        if (result <= 0) {
            // 没有可删除的记录
        }
        return apiCode;
    }
    // endregion

    // region << 直播配置列表 >>
    @Override
    public List<LiveConfigMainModel> findLiveConfigMainModels(ApiQueryBase apiQueryBase) {
        return liveConfigMainMapper.findLiveConfigs(apiQueryBase);
    }

    @Override
    public LiveConfigMainSavedModel findLiveConfigMainModel(String cguid) {
        LiveConfigMainSavedModel liveConfigMainSavedModel = null;

        LiveConfigMain liveConfigMain = liveConfigMainMapper.selectByPrimaryKey(cguid);
        List<LiveDevModel> liveDevModels = equStoreMapper.findLiveDevsByCguid(cguid);
        List<LiveConfigLiveMediaModel> livemedias = liveConfigMediaMapper.findLiveMedias(cguid);
        List<LiveConfigIntercutMediaModel> intercutmedias = liveConfigMediaMapper.findIntercutMedias(cguid);
        List<LiveConfigCarouselMediaModel> carousemedias = liveConfigMediaMapper.findCarouselMedias(cguid);

        if (liveConfigMain != null) {
            liveConfigMainSavedModel = new LiveConfigMainSavedModel();
            liveConfigMainSavedModel.setGuid(liveConfigMain.getGuid());
            liveConfigMainSavedModel.setConfigname(liveConfigMain.getConfigname());
            liveConfigMainSavedModel.setNoticecontent(liveConfigMain.getNoticecontent());
            liveConfigMainSavedModel.setNoticespeed(liveConfigMain.getNoticespeed());
            liveConfigMainSavedModel.setBusdataurl(liveConfigMain.getBusdataurl());
            liveConfigMainSavedModel.setVoicecount(liveConfigMain.getVoicecount());
            liveConfigMainSavedModel.setFlashcount(liveConfigMain.getFlashcount());
            liveConfigMainSavedModel.setIsdebug(liveConfigMain.getIsdebug());

            // 设置关联设备ID集合
            if (liveDevModels != null && liveDevModels.size() > 0) {
                String[] equipNos = new String[liveDevModels.size()];
                for (int i = 0; i < liveDevModels.size(); i++) {
                    equipNos[i] = liveDevModels.get(i).getEquipmentno();
                }
                liveConfigMainSavedModel.setEquipmentnos(equipNos);
            }

            liveConfigMainSavedModel.setLivemedias(livemedias);
            liveConfigMainSavedModel.setIntercutmedias(intercutmedias);
            liveConfigMainSavedModel.setCarousemedias(carousemedias);
        }
        return liveConfigMainSavedModel;
    }

    @Override
    public LiveConfigMainSavedModel findLiveConfigMainModelByEquipmentNo(String equipmentno) {
        LiveConfigMainSavedModel liveConfigMainSavedModel = null;
        DevEquStore devEquStore = equStoreMapper.selectByDevSn(equipmentno);
        if (devEquStore != null && StringUtils.isNoneBlank(devEquStore.getCguid())) {
            liveConfigMainSavedModel = findLiveConfigMainModel(devEquStore.getCguid());
        }
        return liveConfigMainSavedModel;
    }

    @Override
    public ApiCode updateLiveConfigName(String cguid, String configname) {
        ApiCode apiCode = ApiCode.APP_100200;
        LiveConfigMain liveConfigMain = liveConfigMainMapper.selectByPrimaryKey(cguid);
        if (liveConfigMain != null) {
            liveConfigMain.setConfigname(configname);
            liveConfigMainMapper.updateByPrimaryKeySelective(liveConfigMain);
        }
        return apiCode;
    }

    @Override
    public ApiCode saveLiveConfigMain(LiveConfigMainSavedModel liveConfigMainSavedModel, boolean single) {
        ApiCode apiCode = ApiCode.APP_700500;

        if (liveConfigMainSavedModel != null) {

            // region << 有效性校验 >>
            if ((liveConfigMainSavedModel.getLivemedias() == null || liveConfigMainSavedModel.getLivemedias().size() == 0)
                    && (liveConfigMainSavedModel.getIntercutmedias() == null || liveConfigMainSavedModel.getIntercutmedias().size() == 0)
                    && (liveConfigMainSavedModel.getCarousemedias() == null || liveConfigMainSavedModel.getCarousemedias().size() == 0)) {
                apiCode = ApiCode.APP_701500;
            }
            if (!StringUtils.isNoneBlank(liveConfigMainSavedModel.getNoticecontent())) {
                apiCode = ApiCode.APP_701501;
            }
            if (!StringUtils.isNoneBlank(liveConfigMainSavedModel.getBusdataurl())) {
                apiCode = ApiCode.APP_701502;
            }
            if (liveConfigMainSavedModel.getVoicecount() == 0) {
                apiCode = ApiCode.APP_701503;
            }
            if (liveConfigMainSavedModel.getFlashcount() == 0) {
                apiCode = ApiCode.APP_701504;
            }
            if (liveConfigMainSavedModel.getNoticespeed() == 0) {
                apiCode = ApiCode.APP_701505;
            }
            if (liveConfigMainSavedModel.getIntercutmedias() != null && liveConfigMainSavedModel.getIntercutmedias().size() > 0) {
                boolean isHasEmptyTime = false;
                for (int i = 0; i < liveConfigMainSavedModel.getIntercutmedias().size(); i++) {
                    if (!StringUtils.isNoneBlank(liveConfigMainSavedModel.getIntercutmedias().get(i).getStart()) || !StringUtils.isNoneBlank(liveConfigMainSavedModel.getIntercutmedias().get(i).getEnd())) {
                        isHasEmptyTime = true;
                        break;
                    }
                }
                if (isHasEmptyTime) {
                    apiCode = ApiCode.APP_701506;
                } else {
                    // todo 需测试
                    // 判断时间是否有交集
//                    Collections.sort(liveConfigMainSavedModel.getIntercutmedias(), new Comparator<LiveConfigIntercutMediaModel>() {
//                        @Override
//                        public int compare(LiveConfigIntercutMediaModel compare, LiveConfigIntercutMediaModel bycompare) {
//                            if (bycompare.getStart().compareTo(compare.getStart()) >= 0) {
//                                return 1;
//                            }
//                            return 0;
//                        }
//                    });
                    SimpleDateFormat sdf=new SimpleDateFormat("yyyyMMdd HHmmss");
                    // region << 判断开始时间是否小于结束时间>>
                    for(int i=0;i<liveConfigMainSavedModel.getIntercutmedias().size();i++){
                        String startTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(i).getStart()+"00";
                        String endTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(i).getEnd()+"00";
                        try {
                            if(sdf.parse(startTime).getTime()>sdf.parse(endTime).getTime()){
                                return ApiCode.APP_701509;
                            }
                        } catch (ParseException e) {
                            e.printStackTrace();
                        }
                    }
                    // endregion
                    // region << 判断插播视频在两个及以上 >>
                    if(liveConfigMainSavedModel.getIntercutmedias().size()>1){
                        //判断插播时间是否正确:
                            //1.取第一个的时间进行时间格式转换
                            //2.对下一个的时间进行转换
                            //3.判断是否有交集或者包含等
                        for(int i=0;i<liveConfigMainSavedModel.getIntercutmedias().size();i++){
                            ValidateIntercutTime vITime=new ValidateIntercutTime();
                            String startTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(i).getStart()+"00";
                            String endTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(i).getEnd()+"00";
                            try {
                                vITime.setStartTime(sdf.parse(startTime));
                                vITime.setEndTime(sdf.parse(endTime));
                            } catch (ParseException e) {
                                e.printStackTrace();
                            }
                            for(int j=i+1;j<liveConfigMainSavedModel.getIntercutmedias().size();j++){
                                ValidateIntercutTime validateIntercutTime=new ValidateIntercutTime();
                                String sTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(j).getStart()+"00";
                                String eTime="21001010 "+liveConfigMainSavedModel.getIntercutmedias().get(j).getEnd()+"00";
                                try {
                                    validateIntercutTime.setStartTime(sdf.parse(sTime));
                                    validateIntercutTime.setEndTime(sdf.parse(eTime));
                                } catch (ParseException e) {
                                    e.printStackTrace();
                                }
                                if(vITime.getStartTime().getTime()<=validateIntercutTime.getStartTime().getTime()){
                                    if(vITime.getEndTime().getTime()>=validateIntercutTime.getStartTime().getTime()){
                                        return ApiCode.APP_701507;
                                    }
                                    if(vITime.getEndTime().getTime()>=validateIntercutTime.getEndTime().getTime()){
                                        return apiCode.APP_701507;
                                    }
                                }
                                if(vITime.getStartTime().getTime()>=validateIntercutTime.getStartTime().getTime()){
                                    if(vITime.getStartTime().getTime()<=validateIntercutTime.getEndTime().getTime()){
                                        return apiCode.APP_701507;
                                    }
                                    if(vITime.getEndTime().getTime()<=validateIntercutTime.getEndTime().getTime()){
                                        return apiCode.APP_701507;
                                    }
                                }
                            }
                        }
                    }
                    // endregion
                }
            }

            // endregion

            LiveConfigMain liveConfigMain = null;
            boolean isnew = false;
            String guid="";
            if (apiCode.equals(ApiCode.APP_700500)) {
                //判断是否是设备进入,且配置是已存在的配置
                if(single && StringUtil.isNotEmpty(liveConfigMainSavedModel.getGuid())){
                    //只对配置和设备的关系进行修改
                    if (liveConfigMainSavedModel.getEquipmentnos() != null) {
                        for (int i = 0; i < liveConfigMainSavedModel.getEquipmentnos().length; i++) {
                            equStoreMapper.updateLiveConfigId(liveConfigMainSavedModel.getGuid(), liveConfigMainSavedModel.getEquipmentnos()[i]);
                        }
                        return apiCode;
                    }
                }
                liveConfigMain = liveConfigMainMapper.selectByPrimaryKey(liveConfigMainSavedModel.getGuid());
                if (liveConfigMain == null) {
                    isnew = true;
                    liveConfigMain = new LiveConfigMain();
                    guid=UUID.randomUUID().toString();
                    liveConfigMain.setGuid(guid);
                    liveConfigMain.setConfigname(getMaxConfigName("live_configmain", "configname", "新配置"));
                    liveConfigMain.setCreatetime(new Date());
                }
                liveConfigMain.setNoticecontent(liveConfigMainSavedModel.getNoticecontent());
                liveConfigMain.setNoticespeed(liveConfigMainSavedModel.getNoticespeed());
                liveConfigMain.setBusdataurl(liveConfigMainSavedModel.getBusdataurl());
                liveConfigMain.setVoicecount(liveConfigMainSavedModel.getVoicecount());
                liveConfigMain.setFlashcount(liveConfigMainSavedModel.getFlashcount());
                liveConfigMain.setIsdebug(liveConfigMainSavedModel.getIsdebug());

                List<LiveConfigMedia> medias = new ArrayList<>();

                // region << 添加直播资源 >>
                if (liveConfigMainSavedModel.getLivemedias() != null && liveConfigMainSavedModel.getLivemedias().size() > 0) {
                    for (int i = 0; i < liveConfigMainSavedModel.getLivemedias().size(); i++) {
                        LiveConfigMedia media = new LiveConfigMedia();
                        media.setGuid(UUID.randomUUID().toString());
                        media.setCguid(liveConfigMain.getGuid());
                        media.setFileid(liveConfigMainSavedModel.getLivemedias().get(i).getLiveid());
                        media.setSourcetype(LiveConfigSourceType.Live.getIndex());
                        media.setOrderindex(0);
                        if (liveConfigMainSavedModel.getLivemedias().get(i).isDefaultchannel()) {
                            media.setDefaultchannelno(1);
                        } else {
                            media.setDefaultchannelno(0);
                        }
                        media.setCreatetime(new Date());
                        medias.add(media);
                    }
                }
                // endregion

                // region << 添加插播资源 >>
                if (liveConfigMainSavedModel.getIntercutmedias() != null && liveConfigMainSavedModel.getIntercutmedias().size() > 0) {
                    for (int i = 0; i < liveConfigMainSavedModel.getIntercutmedias().size(); i++) {
                        LiveConfigMedia media = new LiveConfigMedia();
                        media.setGuid(UUID.randomUUID().toString());
                        media.setCguid(liveConfigMain.getGuid());
                        media.setFileid(liveConfigMainSavedModel.getIntercutmedias().get(i).getFileid());
                        media.setSourcetype(LiveConfigSourceType.Intercut.getIndex());
                        media.setOrderindex(liveConfigMainSavedModel.getIntercutmedias().get(i).getOrderindex());
                        media.setDefaultchannelno(0);
                        media.setCreatetime(new Date());
                        media.setStart(liveConfigMainSavedModel.getIntercutmedias().get(i).getStart());
                        media.setEnd(liveConfigMainSavedModel.getIntercutmedias().get(i).getEnd());
                        medias.add(media);
                    }
                }
                // endregion

                // region << 添加轮播资源 >>
                if (liveConfigMainSavedModel.getCarousemedias() != null && liveConfigMainSavedModel.getCarousemedias().size() > 0) {
                    for (int i = 0; i < liveConfigMainSavedModel.getCarousemedias().size(); i++) {
                        LiveConfigMedia media = new LiveConfigMedia();
                        media.setGuid(UUID.randomUUID().toString());
                        media.setCguid(liveConfigMain.getGuid());
                        media.setFileid(liveConfigMainSavedModel.getCarousemedias().get(i).getFileid());
                        media.setSourcetype(LiveConfigSourceType.Carousel.getIndex());
                        media.setOrderindex(i);
                        media.setDefaultchannelno(0);
                        media.setCreatetime(new Date());
                        medias.add(media);
                    }
                }
                // endregion

                if (!isnew) {
                    liveConfigMainMapper.updateByPrimaryKey(liveConfigMain);
                } else {

                    liveConfigMainMapper.insert(liveConfigMain);
                }

                liveConfigMediaMapper.deleteMediasByCguid(liveConfigMain.getGuid());
                for (int i = 0; i < medias.size(); i++) {
                    liveConfigMediaMapper.insert(medias.get(i));
                }

                //判断是否是新配置
                if(liveConfigMain == null){
                    if (liveConfigMainSavedModel.getEquipmentnos() != null) {
                        for (int i = 0; i < liveConfigMainSavedModel.getEquipmentnos().length; i++) {
                            equStoreMapper.updateLiveConfigId(guid, liveConfigMainSavedModel.getEquipmentnos()[i]);
                        }
                    }
                }else{
                    // 添加设备配置关联
                    if (!single) {
                        if (liveConfigMainSavedModel.getEquipmentnos() != null) {
                            equStoreMapper.clearConfigId(liveConfigMain.getGuid());
                            for (int i = 0; i < liveConfigMainSavedModel.getEquipmentnos().length; i++) {
                                equStoreMapper.updateLiveConfigId(liveConfigMain.getGuid(), liveConfigMainSavedModel.getEquipmentnos()[i]);
                            }
                        }
                    }else{
                        if (liveConfigMainSavedModel.getEquipmentnos() != null) {
                            for (int i = 0; i < liveConfigMainSavedModel.getEquipmentnos().length; i++) {
                                equStoreMapper.updateLiveConfigId(liveConfigMain.getGuid(), liveConfigMainSavedModel.getEquipmentnos()[i]);
                            }
                        }
                    }
                }

            }
        } else {
            // 配置信息不能为空
        }

        return apiCode;
    }

    @Override
    public ApiCode pushLiveConfig(LiveConfigMainSavedModel liveConfigMainSavedModel, boolean single) {
        ApiCode apiCode = ApiCode.APP_700501;
        if (liveConfigMainSavedModel != null) {
            //判断设备不能为空
            if(liveConfigMainSavedModel.getEquipmentnos() == null || liveConfigMainSavedModel.getEquipmentnos().length == 0){
                return apiCode=ApiCode.APP_701508;
            }
            // 保存直播配置信息
            apiCode = saveLiveConfigMain(liveConfigMainSavedModel, single);

            // 推送直播配置信息
            if (apiCode.equals(ApiCode.APP_700500)) {
                MqPushLiveConfigModel mqPushLiveConfigModel = new MqPushLiveConfigModel();
                mqPushLiveConfigModel.setLiveConfigMainSavedModel(liveConfigMainSavedModel);
                List<MqSelectedDevModel> devs = new ArrayList<>();
                //获取所有的设备信息
                List<DevEquStore> devEquStoreList=equStoreMapper.findAllSitename();
                for (int i = 0; i < liveConfigMainSavedModel.getEquipmentnos().length; i++) {
                    MqSelectedDevModel dev = new MqSelectedDevModel();
                    dev.setDevsn(liveConfigMainSavedModel.getEquipmentnos()[i]);
                    //添加站点名称
                    for(int j=0;j<devEquStoreList.size();j++){
                        if(devEquStoreList.get(j).getDevSn().equals(liveConfigMainSavedModel.getEquipmentnos()[i])){
                            if(StringUtil.isNotEmpty(devEquStoreList.get(j).getSname())){
                                dev.setName(devEquStoreList.get(j).getSname());
                            }
                        }
                    }
                    devs.add(dev);
                }
                mqPushLiveConfigModel.setMqSelectedDevModels(devs);
                iMqService.send2012(mqPushLiveConfigModel);

                apiCode = ApiCode.APP_700501;
            }
        } else {
            // 推送对象不能为空
            apiCode = ApiCode.APP_701500;
        }
        return apiCode;
    }

    private String getMaxConfigName(String tableName, String colName, String modelName) {
        String MaxNo = "";
        //拼接模块
        MaxNo += modelName;
        //获取最大序列号
        String max = liveConfigMainMapper.getMaxConfigName(tableName, colName, modelName);
        if (StringUtils.isNoneBlank(max)) {
            MaxNo += (Integer.parseInt(max) + 1);
        } else {
            MaxNo += 1;
        }

        return MaxNo;
    }

    @Override
    public ApiCode deleteLiveConfig(String cguid) {
        ApiCode apiCode = ApiCode.APP_100200;
        //删除绑定的设备
        equStoreMapper.updateDevEquStoreBycguid(cguid);
        //删除配置关联信息
        liveConfigMediaMapper.deleteMediasByCguid(cguid);
        //删除配置信息
        liveConfigMainMapper.deleteByPrimaryKey(cguid);
        return apiCode;
    }
    // endregion
}